(function(window){
    /*resize分发*/
    var resizeDispatcher = function(){
        var win = $(window);
        var listeners = [],
            data = {w:win.width(),h:win.height()};
        win.bind("resize",function(){
            data = {w:win.width(),h:win.height()};
            dispatch(data);
        });
        function dispatch(data){
            for(var i in listeners){
                if(listeners[i]&&listeners[i].active)
                    if(listeners[i].handler) listeners[i].handler(data);
            }
        }
        function add(data){
            listeners.push(data);
        }
        function getData(){
            return data;
        }
        return {add:add,getData:getData};
    }();

    function getUniqueId(length){                            /*注意：如果范围太小将死循环*/
        var id = "L"+random(length);
        while(find(id,ids))
            id = random(length);
        ids.push(id);
        return id;
    }
    function find(value,target){
        for(var i in target){
            if(target[i] == value)
                return true;
        }
        return false;
    }
    function random(length){
        var min = Math.pow(10,length - 1),
            max = min*10 - 1,
            result = Math.round(min + Math.random()*(max - min));
        return result;
    }

    window.resizeDispatcher = resizeDispatcher;window.getUniqueId = getUniqueId;
})(window);

function log(data){
    if(console)
        console.log(data);
};

function show(obj,visible,duration,callback){
    if(visible)
        if($.support.opacity) {
            obj.stop().fadeIn(duration,callback);
        }
        else{
            obj.show();
            if(callback) callback();
        }
    else
    if($.support.opacity) {
        obj.stop().fadeOut(duration,callback);
    }
    else{
        obj.hide();
        if(callback) callback();
    }
}

function loadData(url,call_back,data){
    jQuery.ajax({
        type:(data && data.method) ? data.method : 'GET',
        url:url,
        data:(data && data.data)?data.data:null,
        dataType:(data && data.dataType)?data.dataType:'json',
        cache:false,
        timeout:60000,
        beforeSend:function (XMLHttpRequest) {
        },
        success:function (data) {
            if(call_back)call_back(data);
        },
        complete:function (XMLHttpRequest, textStatus) {
        },
        error:function (XMLHttpRequest, textStatus, errorThrown) {
            alert("网络发生错误！");
            if(call_back)call_back(null);
        }
    });
}

function find(pattern,target){
     if(pattern && target){
         for(var i in target){
             if(typeof target[i] == "object") {
                 if(target[i].id == pattern) return target[i].name;
             }
             else{
                 if(target[i] == pattern) return true;
             }
         }
     }
}

function merge(from, to){
    for(var i in from){
        if(from.hasOwnProperty(i)){
            to[i] = from[i];
        }
    }
}


$(document).ready(function(){

    var Timer = (function(){

        var clockParent = $("#left-test-time-wrapper > div"),
            ico = $("#left-test-time-wrapper > span:eq(0)")


        var Unit = defineClass(function(time, radix, countDown, lastUnit){

            if(time >= radix || time < 0){
                throw "超出范围";
            }

            this.time = time;
            this.countDown = countDown;
            this.current = countDown ? time : 0;
            this.radix = radix;
            this.htmlElements = [];

            for(var i = 0, length = (radix + "").length; i < length; i++){
                var element = $("<span class='digit'></span>");
                this.htmlElements.push(element);
                clockParent.append(element);
            }

            if(!lastUnit) clockParent.append($("<span class='colon'></span>"));
            this.refreshStyle();

        }, null, {
            htmlElements: null,
            time: 0,
            radix: 60,
            current: 0,
            countDown: false,
            prevUnit: null,
            refreshStyle: function(){

                var digitStr = this.current + "",
                    digitStr2 = this.radix + "";

                while(digitStr.length < digitStr2.length){
                    digitStr = "0" + digitStr;
                }

                for(var i = 0, length = (this.radix + "").length; i < length; i++){
                    this.htmlElements[i].removeClass().addClass("digit digit" + digitStr.charAt(i));
                }

            },
            step: function(){                          /*改~~~~~~~~~~~~~~~~~*/
                if(this.countDown){
                    if(this.current == 0){
                        if(!(this.prev && this.prev.step())){
                            return false;
                        }
                        this.time = this.radix;
                        this.current = this.radix;
                    }
                    this.current -= 1;
                    this.refreshStyle();
                    return true;
                }

                if(this.current + 1 == this.radix){
                    if(!(this.prev && this.prev.step())){
                        return false;
                    }
                    this.time = 0;
                }
                this.current += 1;
                this.refreshStyle();
                return true;

               // this.current += 1 + -2 * this.countDown;

            }
        });


        var Timer = defineClass(function(time, countDown, duration, callback){

            if(time > 86399 || time < 1) throw "超出范围";

            var 时 = new Unit(Math.floor(time/3600), 24, countDown);

            time = time - Math.floor(time/3600) * 3600

            var 分 = new Unit(Math.floor(time/60), 60, countDown);

            time = time - Math.floor(time/60) * 60;

            var 秒 = new Unit(time, 60, countDown, true);

            /*var 毫秒 = new Unit(98, 99, countDown, true);

            毫秒.prev = 秒;*/
            秒.prev = 分;
            分.prev = 时;

            var icoInterval = setInterval(function(){
                if(ico.is(":visible")) show(ico, false, 300);
                else show(ico, true, 300);
            }, 1000);

            var interval = setInterval(function(){
                if(!秒.step()){
                    clearInterval(interval);
                    clearInterval(icoInterval);
                    show(ico, true, 300);
                    callback();
                }
            }, duration);

        }, null, {
            start: function(){

            },
            pause: function(){

            },
            reset: function(){

            },
            stop: function(){

            }
        });

        return Timer;

    })();



    var Event = (function(window){

        var events = {

        }

        function log(msg){
            if(window.console) console.log(msg);
        }

        function define(eventType){
            if(!events[eventType])
                events[eventType] = [];
        }

        function on(eventType, callback){
            if(!events[eventType]){
                define(eventType);
            }
            events[eventType].push(callback);
        }

        function trigger(eventType){
            if(events[eventType]){
                for(var i = 0, fns = events[eventType], length = fns.length; i < length; i++){
                    if(fns[i]() == false) break;
                }
            }
        }

        return {
            on: on,
            trigger: trigger,
            destroy: function(eventType){
                if(!eventType){
                    events = {};
                }
                else{
                    events[eventType] = [];
                }
            }
        };

    })(window),
    Queue = (function(window){

        var queues = {

        }

        function log(msg){
            if(window.console) console.log(msg);
        }

        function define(queueType){
            if(!queues[queueType])
                queues[queueType] = [];
        }

        function add(queueType, callback){
            if(!queues[queueType]){
                define(queueType);
            }
            queues[queueType].push(callback);
        }

        function exec(queueType){
            if(queues[queueType]){
                for(var i = 0, fns = queues[queueType], length = fns.length; i < length; i++){
                    if(fns[i]() == false) break;
                }
            }
        }

        return {
            add: add,
            exec: exec
        };

    })(window),
    timer = new Timer(restSecond, true, 1000, function(){
        alert("时间到，您的试卷已经保存")
    }),
    frame = questionFrame,
    questionInterface = frame.questionInterface;

    Queue.add("prev", function(){

        if(current > 0){
            if(canDirectGet()){
                directGet(questions[current - 1].qId);
            }
            else{
                formGet(questions[current - 1].qId);
            }
        }
        else{
            alert("已经是第一题了");
        }
    });

    Queue.add("next", function(){

        if(current < questions.length - 1){
            if(canDirectGet()){
                directGet(questions[current + 1].qId);
            }
            else{
                formGet(questions[current + 1].qId);
            }
        }
        else{
            alert("已经是最后一题了");
        }
    });

    Queue.add("submit", function(){
        var status = canSubmit(questions);
        if(status != true){
            return confirm(status + "，是否继续？");
        }
    });
    Queue.add("submit", function(){
        alert("submited");
    });





    Event.on("prev", function(){
        Queue.exec("prev");
    });

    Event.on("next", function(){
        Queue.exec("next");
    });

    Event.on("submit", function(){
        Queue.exec("submit");
    });





    $("#test-prev").click(function(){
        Event.trigger("prev");
    });

    $("#test-next").click(function(){
        Event.trigger("next");
    });

    $("#test-submit").click(function(){
        Event.trigger("submit");
    });



    window.testInterface = {
        setCurrentAnswer: function(qId, currentAnswer){
            var questionArray = questions;
            for(var i = 0, length = questionArray.length; i < length; i++){
                if(qId == questionArray[i].qId){
                    questionArray[i].currentAnswer = currentAnswer;
                }
            }
        },
        setValidated: function(qId, flag){
            var questionArray = questions;
            for(var i = 0, length = questionArray.length; i < length; i++){
                if(qId == questionArray[i].qId){
                    questionArray[i].validated = flag;
                }
            }
        },
        notify: function(data){
            questionInterface = data.questionInterface;
            var questionArray = questions;
            if(data.qId){
                for(var i = 0, length = questionArray.length; i < length; i++){
                    if(data.prevQId && data.prevAnswer && data.prevQId == questionArray[i].qId){
                        questionArray[i].answer = data.prevAnswer;
                        questionArray[i].saved = true;
                    }
                    if(data.qId == questionArray[i].qId){
                        current = i;
                        questionInterface.setAnswer(questionArray[i].answer);
                    }
                }
            }

            this.loaded();

            log("prevQId = " + data.prevQId + "\n" + "prevAnswer = " + data.prevAnswer);
        },
        loading: function(){
            $(loader).show();
        },
        loaded: function(){
            $(loader).hide();
        },
        finished:function(){
            Event.destroy();
        },
        Event: Event,
        Queue: Queue
    }



    function canDirectGet(){
        var flag  =  questions[current].currentAnswer == questions[current].answer || !confirm("是否保存？");

        if(flag){
            questions[current].currentAnswer = questions[current].answer;
        }

        return flag;
    }

    function canSubmit(questions){

        for(var i = 0, length = questions.length; i < length; i++){
            if(!questions[i].saved){
                return "有未完成试题";
            }
            if(questions[i].currentAnswer != questions[i].answer){
                return "有未保存试题";
            }

        }

        return true;

    }

    function confirm(msg){
        return window.confirm(msg);
    }

    function directGet(manualQId){
        frame.location = questionUrl + "?manualQId=" + manualQId;
    }

    function formGet(manualQId){
        questionInterface.questionPageTo(manualQId);
    }

});


function log(msg){
    if(window.console && window.console.log)
        console.log(msg);
}

function defineClass(constructor, parent, properties, statics, isSingleton){
    if(isSingleton){
        var instance, oldConstructor = constructor;
        constructor = function(){
            if(instance) return instance;
            oldConstructor.call(this);
            instance = this;
        }
    }
    constructor.prototype = parent ? new parent : {};
    merge(properties, constructor.prototype);
    merge(statics, constructor);
    constructor.prototype.constructor = constructor;
    return constructor;
}